const app = getApp();
const api = require('../../utils/api');

Page({
  data: {
    useRealApi: false,
    envType: 'dev',
    envVersion: 'develop',
    apiEndpoint: '',
    databaseStats: {
      glucose: 0,
      bloodPressure: 0,
      weight: 0,
      users: 0
    },
    storageStats: {
      glucose: 0,
      bloodPressure: 0,
      weight: 0
    },
    loading: false,
    testResult: '',
    testStatus: ''
  },

  onLoad: function() {
    // 获取当前API模式
    this.setData({
      useRealApi: app.globalData.useRealApi,
      envType: app.globalData.envType,
      envVersion: app.globalData.envVersion,
      apiEndpoint: api.getApiEndpoint ? api.getApiEndpoint() : '未知'
    });
    
    // 加载数据统计
    this.loadStorageStats();
  },
  
  onShow: function() {
    // 重新加载配置和统计
    this.setData({
      useRealApi: app.globalData.useRealApi
    });
    this.loadStorageStats();
  },
  
  // 加载本地存储统计信息
  loadStorageStats: function() {
    try {
      const glucoseData = wx.getStorageSync('health_glucose') || [];
      const bpData = wx.getStorageSync('health_bloodPressure') || [];
      const weightData = wx.getStorageSync('health_weight') || [];
      
      this.setData({
        'storageStats.glucose': glucoseData.length,
        'storageStats.bloodPressure': bpData.length,
        'storageStats.weight': weightData.length
      });
    } catch (error) {
      console.error('获取存储统计失败:', error);
    }
  },
  
  // 切换API模式
  toggleApiMode: function() {
    const result = app.toggleApiMode();
    if (result !== false) {
      this.setData({
        useRealApi: result,
        testResult: result ? '已切换到真实API模式' : '已切换到模拟数据模式',
        testStatus: 'success'
      });
      
      // 更新UI提示
      wx.showToast({
        title: result ? '已启用真实API' : '已启用模拟数据',
        icon: 'success'
      });
    }
  },
  
  // 测试数据库连接
  testDbConnection: function() {
    this.setData({
      loading: true,
      testResult: '正在测试数据库连接...',
      testStatus: 'loading'
    });
    
    if (!app.globalData.useRealApi) {
      // 如果未启用真实API，先切换
      app.toggleApiMode();
      this.setData({ useRealApi: true });
      
      wx.showToast({
        title: '已切换至真实API',
        icon: 'none',
        duration: 1000
      });
    }
    
    // 执行API调用测试数据库连接
    api.testDatabaseConnection().then(res => {
      console.log('数据库测试结果:', res);
      
      this.setData({
        loading: false,
        testResult: res.success ? '数据库连接成功' : '数据库连接失败: ' + res.message,
        testStatus: res.success ? 'success' : 'error',
        'databaseStats.glucose': res.data?.glucoseCount || 0,
        'databaseStats.bloodPressure': res.data?.bloodPressureCount || 0,
        'databaseStats.weight': res.data?.weightCount || 0,
        'databaseStats.users': res.data?.userCount || 0
      });
    }).catch(err => {
      console.error('测试数据库连接出错:', err);
      
      this.setData({
        loading: false,
        testResult: '测试失败: ' + (err.message || '未知错误'),
        testStatus: 'error'
      });
    });
  },
  
  // 清除本地存储
  clearLocalStorage: function() {
    wx.showModal({
      title: '确认清除',
      content: '确定要清除所有本地健康数据存储吗？此操作不可撤销。',
      success: (res) => {
        if (res.confirm) {
          try {
            wx.removeStorageSync('health_glucose');
            wx.removeStorageSync('health_bloodPressure');
            wx.removeStorageSync('health_weight');
            
            this.setData({
              'storageStats.glucose': 0,
              'storageStats.bloodPressure': 0,
              'storageStats.weight': 0,
              testResult: '本地存储清除成功',
              testStatus: 'success'
            });
            
            wx.showToast({
              title: '存储已清除',
              icon: 'success'
            });
          } catch (error) {
            console.error('清除存储失败:', error);
            this.setData({
              testResult: '清除失败: ' + error.message,
              testStatus: 'error'
            });
          }
        }
      }
    });
  },
  
  // 导出测试数据
  exportTestData: function() {
    this.setData({
      loading: true,
      testResult: '准备导出数据...',
      testStatus: 'loading'
    });
    
    try {
      const glucoseData = wx.getStorageSync('health_glucose') || [];
      const bpData = wx.getStorageSync('health_bloodPressure') || [];
      const weightData = wx.getStorageSync('health_weight') || [];
      
      const exportData = {
        glucose: glucoseData,
        bloodPressure: bpData,
        weight: weightData,
        timestamp: new Date().toISOString(),
        deviceInfo: wx.getSystemInfoSync()
      };
      
      // 将数据保存为临时文件
      const exportStr = JSON.stringify(exportData);
      
      // 由于微信小程序环境限制，这里我们只能显示导出信息
      console.log('导出数据:', exportStr);
      
      this.setData({
        loading: false,
        testResult: `已导出数据(${glucoseData.length}条血糖,${bpData.length}条血压,${weightData.length}条体重)，请在控制台查看`,
        testStatus: 'success'
      });
    } catch (error) {
      console.error('导出数据失败:', error);
      this.setData({
        loading: false,
        testResult: '导出失败: ' + error.message,
        testStatus: 'error'
      });
    }
  },
  
  // 跳转到血压数据生成器
  goToBloodPressureGenerator: function() {
    wx.navigateTo({
      url: '/pages/test/datagen'
    });
  },
  
  // 跳转到血糖数据生成器
  goToGlucoseGenerator: function() {
    wx.navigateTo({
      url: '/pages/test/glucose-datagen'
    });
  },
  
  // 跳转到体重数据生成器
  goToWeightGenerator: function() {
    wx.navigateTo({
      url: '/pages/test/weight-datagen'
    });
  }
}); 